package cn.chencaiju.blog.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.chencaiju.blog.domain.AjaxResponse;
import cn.chencaiju.blog.domain.Post;
import cn.chencaiju.blog.service.PostService;
import cn.chencaiju.blog.utils.ServiceProxyUtils;


@WebServlet(
		urlPatterns= {"/post/page","/post/delbat","/post/insert","/post/search"})
public class PostServlet extends BaseServlet{
	private PostService service=(PostService) ServiceProxyUtils.createProxy(new PostService());
	
	public void page(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		System.out.println("post page");
		String pages = req.getParameter("page");
		String limit = req.getParameter("limit");
		AjaxResponse<Post> response = service.page(pages,limit);
		if(response!=null) {
			String jsonString = JSON.toJSONString(response);
			resp.setContentType("application/json;charset=utf-8");
			resp.getWriter().write(jsonString);
		}		
	}	
	/**
	 * 批量删除文章
	 */
	public void delbat(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		System.out.println("post delbat");
		String[] ids = req.getParameterMap().get("ids");
		if(ids!=null) {
			service.deleteBatch(ids);
		}
	}
	
	public void insert(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		String title = req.getParameter("title");
		String cid = req.getParameter("category");
		String content = req.getParameter("content");
		String created=req.getParameter("date");
		service.insert(title,cid,content,created);
		
	}
	
	public void search(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		System.out.println("search...");
		String title = req.getParameter("title");
		String cid = req.getParameter("category");
		String created = req.getParameter("created");
		
		List<Post> post = service.search(title,cid,created);
		System.out.println(post);
		writeListData(resp, post);
	}
}
